import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import { defineConfig, loadEnv, ConfigEnv } from 'vite'
import vueSetupExtend from 'vite-plugin-vue-setup-extend-plus'
import viteCompression from 'vite-plugin-compression'
import AutoImport from 'unplugin-auto-import/vite'
import { createStyleImportPlugin, VxeTableResolve } from 'vite-plugin-style-import'

const pathResolve = (dir: string) => {
	return resolve(__dirname, '.', dir)
}

const alias: Record<string, string> = {
	'@': pathResolve('./src/'),
}

const viteConfig = defineConfig((mode: ConfigEnv) => {
	const env = loadEnv(mode.mode, process.cwd())
	return {
		plugins: [
			vue(),
			vueSetupExtend(),
			viteCompression(),
			AutoImport({
				imports: ['vue', 'vue-router', 'pinia'], //自动引入vue的ref、toRefs、onmounted等，无需在页面中再次引入
				dts: 'src/types/auto.d.ts',
			}),
			createStyleImportPlugin({
				resolves: [VxeTableResolve()],
			}),
		],
		root: process.cwd(),
		resolve: { alias },
		base: mode.command === 'serve' ? './' : env.VITE_PUBLIC_PATH,
		optimizeDeps: {
			exclude: ['vue-demi'],
		},
		server: {
			host: '0.0.0.0',
			port: env.VITE_PORT as unknown as number,
			open: JSON.parse(env.VITE_OPEN),
			hmr: true,
			proxy: {
				'/gateway': {
					target: 'http://10.100.30.62:28880',
					ws: true,
					changeOrigin: true,
					rewrite: path => path.replace(/^\/gateway/, ''),
				},
			},
		},
		build: {
			outDir: 'dist',
			chunkSizeWarningLimit: 1500,
			rollupOptions: {
				output: {
					chunkFileNames: 'assets/js/[name]-[hash].js',
					entryFileNames: 'assets/js/[name]-[hash].js',
					assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
					manualChunks(id) {
						if (id.includes('node_modules')) {
							return id.toString().match(/\/node_modules\/(?!.pnpm)(?<moduleName>[^/]*)\//)?.groups!.moduleName ?? 'vender'
						}
					},
				},
			},
		},
		css: {
			preprocessorOptions: {
				css: {
					charset: false,
				},
				scss: {
					// 文件路径，注意最后需要添加 ';'
					additionalData: '@import "@/theme/screen.scss";',
					javascriptEnabled: true,
				},
			},
		},
		define: {
			__NEXT_VERSION__: JSON.stringify(process.env.npm_package_version),
		},
	}
})

export default viteConfig
